const router = require('koa-router')()
const dbs = require('../../mysql/index').isconnect()

router.post('/login', async ctx => {
  let { userid, password } = ctx.request.body
  if (String(ctx.request.body) == '{}') {
    ctx.body = { code: 10000, result: '请输入账号密码' }
  } else if (!userid || !password) {
    ctx.body = { code: 10000, result: '请输入完整账号密码' }
  } else {
    ctx.body = { code: 200, result: '登录成功' }
  }
})

router.post('/register', async ctx => {
  let { userid, password } = ctx.request.body
  if (Object.keys(ctx.request.body).length !== 2) {
    ctx.body = { code: 10000, result: '未获取表单数据' }
  } else if (userid === undefined || password === undefined) {
    ctx.body = { code: 10000, result: '数据不整' }
  } else if (userid === '' || password === '') {
    ctx.body = { code: 10000, result: '用户名或密码为空' }
  } else {
    let res = await dbs.find('userid', 'user', `userid=${userid}`)
    if (res.length == 0) {
      // 获取到的是空数组 可以插入数据
      let res1 = await dbs.insert(
        'user',
        `(${userid},'${password}')`,
        'backstage'
      )
      if (res1.code == 1) {
        ctx.body = { code: 200, result: '请求成功' }
      } else {
        ctx.body = { code: 10000, result: '注册失败，请检查数据并反馈' }
      }
    } else {
      ctx.body = { code: 10000, result: '改用户名已经被注册' }
    }
  }
})

module.exports = router.routes()
